﻿using Microsoft.EntityFrameworkCore;
using System.IO;
using XYAC.Framework.MonitorTireMaterialManual.Entities;

namespace XYAC.Framework.MonitorTireMaterialManual.Context
{
    /// <summary>
    /// 本地SQLite的数据库上下文。
    /// </summary>
    public abstract class ReportContext : DbContext
    {

        private bool isEnsureCreate;
        private bool? _dbFileCreated;

        public bool IsEnsureCreate
        {
            get
            {
                if (!isEnsureCreate)
                {
                    isEnsureCreate = Database.EnsureCreated();
                }
                return isEnsureCreate;
            }
        }

        public virtual DbSet<SemiSteelSideInspectionReport> SemiSteelSideInspectionReport { get; set; } = null!;
        public virtual DbSet<SemiSteelTreadScanReport> SemiSteelTreadScanReport { get; set; } = null!;
        public virtual DbSet<SemiSteelTriangleRubberReport> SemiSteelTriangleRubberReport { get; set; } = null!;
        public virtual DbSet<PreCheckReport> PreCheckReport { get; set; } = null!;
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public bool GetDbFileCreated()
        {
            if (!_dbFileCreated.HasValue)
            {
                string connectionStr = Database.GetConnectionString();

                // 提取 Data Source 的值
                var dataSourceIndex = connectionStr.IndexOf("Data Source=", StringComparison.OrdinalIgnoreCase);
                if (dataSourceIndex < 0)
                {
                    throw new InvalidOperationException("连接字符串中未找到 'Data Source='。");
                }

                // 提取数据库文件路径部分（直到第一个分号或字符串结尾）
                int endIndex = connectionStr.IndexOf(";", dataSourceIndex);
                var dbFilePath = endIndex > dataSourceIndex
                    ? connectionStr.Substring(dataSourceIndex + "Data Source=".Length, endIndex - dataSourceIndex - "Data Source=".Length).Trim()
                    : connectionStr.Substring(dataSourceIndex + "Data Source=".Length).Trim();

                // 获取完整路径并检查文件是否存在
                var fullPath = Path.GetFullPath(dbFilePath);
                var directory = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                _dbFileCreated = File.Exists(fullPath);
            }

            return _dbFileCreated.Value;
        }

    }
}
